﻿namespace VirtualTemplates
{
    using System.Diagnostics.Contracts;
    using System.IO;
    using System.Resources;
    using System.Web.Hosting;

    /// <summary>
    /// A virtual file that maps to a resource in an assembly.
    /// </summary>
    internal class AssemblyVirtualFile : VirtualFile
    {
        private readonly ResourceManager resourceManager;

        private readonly string resourceName;

        /// <summary>
        /// Initializes a new instance of the <see cref="AssemblyVirtualFile"/> class.
        /// </summary>
        /// <param name="resourceManager">The resource manager.</param>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="virtualPath">The virtual path.</param>
        public AssemblyVirtualFile(ResourceManager resourceManager, string resourceName, string virtualPath)
            : base(virtualPath)
        {
            Contract.Requires(resourceManager != null);

            this.resourceManager = resourceManager;
            this.resourceName = resourceName;
        }

        /// <summary>
        /// Returns a read-only stream to the resource in the assembly.
        /// </summary>
        /// <returns>
        /// A read-only stream to the resource in the assembly.
        /// </returns>
        public override Stream Open()
        {
            return (Stream)this.resourceManager.GetObject(this.resourceName);
        }
    }
}
